﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using System.Web;

namespace Hx.ADSyncPlatform.Common
{
    public static class ToolCommon
    {

        #region 根据业务封装方法

        /// <summary>
        /// 获取配置文件中的密钥值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public static string GetConfig(string key)
        {
            string ReturnStr = System.Configuration.ConfigurationManager.AppSettings[key];
            return ReturnStr;
        }

        /// <summary>
        /// 将实体类转换成为JSON
        /// </summary>
        /// <typeparam name="T">Model类型</typeparam>
        /// <param name="model">实例化后的实体类</param>
        /// <returns>json串</returns>
        public static string GetJson<T>(T model)
        {
            return JsonConvert.SerializeObject(model);
        }

        /// <summary>
        /// 将json串转换成为对应实体类
        /// </summary>
        /// <typeparam name="T">Model类型</typeparam>
        /// <param name="json">json串</param>
        /// <returns>Model</returns>
        public static T GetModel<T>(string json)
        {
            T t = default(T);
            if (json == null)
            {
                return t;
            }
            t = JsonConvert.DeserializeObject<T>(json);
            return t;
        }


        /// <summary>
        /// 将dataset转换为对应实体类
        /// </summary>
        /// <typeparam name="T">Model类型</typeparam>
        /// <param name="ds">DataSet</param>
        /// <returns></returns>
        public static T GetModelDS<T>(DataSet ds)
        {
            DataTable dt = ds.Tables?[0];
            if (dt != null)
            {
                T t = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(dt));
                return t;
            }
            else
                return default(T);
        }

        /// <summary>
        /// Url编码
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <returns></returns>
        public static string UrlEncode(string parameter)
        {
            return HttpUtility.UrlEncode(parameter);
        }

        /// <summary>
        /// Url解码
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <returns></returns>
        public static string UrlDecode(string parameter)
        {
            return HttpUtility.UrlDecode(parameter);
        }

        /// <summary>
        /// 将GUID转换为string类型的8进制字符串
        /// </summary>
        /// <param name="objectGuid">guid</param>
        /// <returns></returns>
        public static string Guid2OctetString(Guid objectGuid)
        {
            byte[] byteGuid = objectGuid.ToByteArray();
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteGuid)
            {
                sb.Append(@"\" + b.ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 把 字符串  转换为 MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MD5(string value)
        {
            byte[] pasArray = System.Text.Encoding.Default.GetBytes(value);
            pasArray = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(pasArray);
            string rMd5Str = "";
            foreach (byte ibyte in pasArray)
                rMd5Str += ibyte.ToString("x").PadLeft(2, '0');
            return rMd5Str;
        }

        /// <summary>
        /// 将DataTable转换为List对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ConvertToModel<T>(DataTable dt) where T : new()
        {
            List<T> ts = new List<T>();// 定义集合
            if (dt == null || dt.Rows.Count == 0)
            {
                return default;
            }
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                foreach (PropertyInfo pi in propertys)
                {
                    //获取属性名称
                    String name = pi.Name;
                    if (dr.Table.Columns.Contains(name))
                    {
                        //非泛型
                        if (!pi.PropertyType.IsGenericType)
                        {
                            pi.SetValue(t, string.IsNullOrEmpty(dr[name].ToString()) ? null : Convert.ChangeType(dr[name], pi.PropertyType), null);
                        }
                        //泛型Nullable<>
                        else
                        {
                            Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
                            //model属性是可为null类型，进行赋null值
                            if (genericTypeDefinition == typeof(Nullable<>))
                            {
                                //返回指定可以为 null 的类型的基础类型参数
                                pi.SetValue(t, string.IsNullOrEmpty(dr[name].ToString()) ? null : Convert.ChangeType(dr[name], Nullable.GetUnderlyingType(pi.PropertyType)), null);
                            }
                        }
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

        #endregion
    }
    public class ErrorModel
    {
        public string StatusCode { get; set; }
        public string Error { get; set; }
        public string Message { get; set; }
    }
}
